package com.siro.auth.base.common.domain;

import com.siro.auth.base.constant.ResultCode;
import lombok.Data;

/**
 * 全局统一返回结果集
 *
 * @author starsea
 * @date 2022-07-13 11:07
 */
@Data
public class Result<T> {
    /**
     * 是否成功
     */
    private Boolean success;

    /**
     * 状态码
     */
    private Integer code;
    /**
     * 返回消息
     */
    private String message;
    /**
     * 返回数据
     */
    private T data;

    public Result() {
    }

    /**
     * 成功执行，未返回数据
     * @param <T>
     * @return
     */
    public static <T> Result<T> ok() {
        return restResult(true,null, ResultCode.SUCCESS, "执行成功");
    }

    /**
     * 执行成功，并返回数据
     * @param data
     * @param <T>
     * @return
     */
    public static <T> Result<T> ok(T data) {
        return restResult(true,data, ResultCode.SUCCESS, "执行成功");
    }

    /**
     * 执行失败
     * @param <T>
     * @return
     */
    public static <T> Result<T> fail() {
        return restResult(false,null, ResultCode.ERROR, "执行失败");
    }

    /**
     * 执行失败
     * @param status
     * @param msg
     * @param <T>
     * @return
     */
    public static <T> Result<T> fail(Integer status, String msg) {
        return restResult(false,null, status, msg);
    }

    /**
     * 执行失败
     * @param msg
     * @param <T>
     * @return
     */
    public static <T> Result<T> fail(String msg) {
        return restResult(false,null, ResultCode.ERROR, msg);
    }

    /**
     * 设置是否成功
     * @param success
     * @return
     */
    public Result<T> success(Boolean success) {
        this.setSuccess(success);
        return this;
    }

    /**
     * 设置状态码
     * @param code
     * @return
     */
    public Result<T> code(Integer code) {
        this.setCode(code);
        return this;
    }

    /**
     * 设置返回消息
     * @param msg
     * @return
     */
    public Result<T> message(String msg) {
        this.setMessage(msg);
        return this;
    }

    private static <T> Result<T> restResult(Boolean success, T data, int code, String msg) {
        Result<T> apiResult = new Result<>();
        apiResult.setSuccess(success);
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMessage(msg);
        return apiResult;
    }
}
